﻿using System;
using System.Linq;
using Loki.UI;

namespace Luna.UI.Wpf
{
    /// <summary>
    /// Interaction logic for TabContainer.xaml
    /// </summary>
    public partial class TabContainer : Loki.UI.Wpf.ViewControl<OpenDocumentsViewModel>
    {
        public TabContainer()
        {
            InitializeComponent();
            this.Loaded += TabContainer_Loaded;
            documentContainer.SelectedItemChanged += documentContainer_SelectedItemChanged;
            DataContextChanged += TabContainer_DataContextChanged;
        }

        private void documentContainer_SelectedItemChanged(object sender, DevExpress.Xpf.Docking.Base.SelectedItemChangedEventArgs e)
        {
            if (e.OldItem != null)
            {
                var L_OldViewModel = e.OldItem.DataContext as IViewModel;

                if (L_OldViewModel != null && L_OldViewModel.IsActive)
                {
                    L_OldViewModel.Desactivate.Execute(null);
                }
            }

            if (e.Item != null)
            {
                var L_NewViewModel = e.Item.DataContext as IViewModel;

                if (L_NewViewModel != null && !L_NewViewModel.IsActive)
                {
                    L_NewViewModel.Activate.Execute(null);
                }
            }
        }

        private void TabContainer_DataContextChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            if (ViewModel != null)
            {
                ViewModel.SubModelActivated += ViewModel_SubModelActivated;
            }
        }

        private void TabContainer_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (ViewModel != null && ViewModel.SubModels.Any() && ViewModel.ActiveDocument != null)
            {
                documentContainer.SelectedTabIndex = ViewModel.SubModels.ToList().IndexOf(ViewModel.ActiveDocument);
            }
        }

        private void ViewModel_SubModelActivated(object sender, ViewModelEventArgs e)
        {
            if (ViewModel.SubModels.Any() && e.ViewModel != null)
            {
                Console.WriteLine(e.ViewModel.GetType() + "Activated");

                documentContainer.SelectedTabIndex = ViewModel.SubModels.ToList().IndexOf(e.ViewModel);
            }
        }
    }
}